package com.zhang.backend.controller;

import com.zhang.backend.dto.PersonDetailDTO;
import com.zhang.backend.entity.Person;
import com.zhang.backend.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/persons")
public class PersonController {

    @Autowired
    private PersonService personService;

    @PostMapping
    public ResponseEntity<Person> addPerson(@RequestBody Person person) {
        personService.save(person);
        return ResponseEntity.ok(person);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Person> getPersonById(@PathVariable Long id) {
        Person person = personService.getById(id);
        return person != null ? ResponseEntity.ok(person) : ResponseEntity.notFound().build();
    }

    @GetMapping
    public ResponseEntity<List<Person>> getAllPersons() {
        List<Person> persons = personService.list();
        return ResponseEntity.ok(persons);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Person> updatePerson(@PathVariable Long id, @RequestBody Person personDetails) {
        personDetails.setPersonId(id);
        personService.updateById(personDetails);
        return ResponseEntity.ok(personDetails);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deletePerson(@PathVariable Long id) {
        personService.removeById(id);
        return ResponseEntity.noContent().build();
    }
    // 【新增】获取人员详细信息的接口
    @GetMapping("/{id}/details")
    public ResponseEntity<PersonDetailDTO> getPersonDetails(@PathVariable Long id) {
        PersonDetailDTO details = personService.getPersonDetails(id);
        return details != null ? ResponseEntity.ok(details) : ResponseEntity.notFound().build();
    }
}